package com.hst.web.sys.quartz;

import java.io.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.hst.core.dao.IORDao;
import com.hst.core.dao.ISQLDao;
import com.hst.core.excel.views.HSExcel2;
import com.hst.web.base.po.CheckPendingPersonPO;
import com.hst.web.base.po.CheckPendingVehiclePO;
import com.hst.web.common.utils.DateTimeUtil;

/**
 * @Description: Excel数据导出定时任务
 * @Author: duyong
 * @Date:
 */
@Component
@EnableScheduling   // 开启定时任务
public class ExcelExportQuartz {
	Logger logger = LoggerFactory.getLogger(ExcelExportQuartz.class);
	String oldPath = "../filestore";
	String newPath = "../temp/employeeface";
	int before = 7, after = 3;
	String path = "../temp";

	@Autowired
	IORDao dao;

	@Autowired
	ISQLDao sql;

	//待审批数据导出,导出公安管理员待审批人员车辆信息和人员照片数据
	//添加定时任务
	//@Scheduled(cron = "0 0 0,12 * * ?")		//每天0、12点触发一次
	//@Scheduled(cron = "0 0/10 * * * ?")		//每隔10分钟触发一次
	@Scheduled(cron = "0 30 10 * * ?")			//每天10:30点触发一次
	//@Scheduled(cron = "0 0 15 * * ?")			//每天15:00点触发一次
	public void checkPendingDataExp() {
		try {
			expCheckPendingData();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//待审批数据导出,导出公安管理员待审批人员车辆信息和人员照片数据(15:00)
	@Scheduled(cron = "0 0 15 * * ?")			//每天15:00点触发一次
	public void checkPendingDataExp1500() {
		try {
			expCheckPendingData();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}	

	/**
	 * 导出公安管理员待审批人员车辆信息和人员照片数据
	 * @return
	 * @throws Exception
	 */
	public void expCheckPendingData() throws Exception {
		Map<String, Object> params = new HashMap<>();

		//生成待审核人员数据
		List<CheckPendingPersonPO> personList = getCheckPendingPerson(params);
		buildCheckPendingPerson(personList);

		//生成待审核人员照片

		FileOutputStream fileOutputStream = new FileOutputStream(new File("../temp/待审批核对人员信息"+DateTimeUtil.getCurrDate("yyyyMMddHH")+".rar"));

		File excelFile = new File("../temp/待审批核对人员信息"+DateTimeUtil.getCurrDate("yyyyMMddHH")+".xlsx");
		File imgDir = new File("../temp/employeeface");
		List<File> fileList = new ArrayList<>();
		fileList.add(imgDir);
		fileList.add(excelFile);

		try {
			//复制，压缩文件
			List<CheckPendingPersonPO> personPOList = getCheckPendingPerson(params);
			buildCheckPendingPhoto(oldPath,newPath,personPOList);

			//压缩待审核人员照片和excel表格
			zipFiles(fileList,fileOutputStream);

			//清空employeeface文件夹下照片
			delFile(newPath);

			//清空过期文件  (temp目录下)
			delExpiredFile(before,after,path);
		} catch (Exception e) {
			e.printStackTrace();
		}

		//生成待审核车辆数据
		List<CheckPendingVehiclePO> vehicleList = getCheckPendingVehicle(params);
		buildCheckPendingVehicle(vehicleList);

	}

	/**
	 * 生成待审核人员Excel文件
	 * @return
	 * @throws Exception
	 */
	public void buildCheckPendingPerson(List<CheckPendingPersonPO> personList)throws IOException{
		int i = 0;
		for (CheckPendingPersonPO p : personList) {
			if (p != null){
				if (p.getPapersNumber() != null) {
					if (p.getPicPath() != null) {
						p.setPicPath("employeeface" + "/" + p.getPapersNumber() + p.getDynamicFace().substring(p.getDynamicFace().lastIndexOf(".")));
					}
				}
//				if (p.getPassOld() != null || p.getFullName() != null || p.getDynamicFace() != null || p.getPapersNumber() != null || p.getContractorName() != null || p.getCompanyName() != null){
					p.setSerialId(i+1);
					i++;
//				}
			}
		}
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("data00", personList);
		dataMap.put("curDate", DateTimeUtil.getCurrDate("yyyy-MM-dd HH:mm"));
		//先生成Excel表
		XSSFWorkbook workbook = new XSSFWorkbook();
		try {
			//模板默认地址为"/WEB-INF/xls/",因此需要加模块路径
			HSExcel2 hsExcel2= new HSExcel2();
			hsExcel2.setTemplateName("xls/checkpendingperson");
			hsExcel2.buildExcelDocument(dataMap, workbook);

		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			try {
				workbook.close();
				workbook = null;
			} catch (IOException e) {}
		}
		copyFile("../temp/CheckPendingPerson.xlsx", "../temp/待审批核对人员信息"+DateTimeUtil.getCurrDate("yyyyMMddHH")+".xlsx");
	}

	/**
	 * 生成待审核车辆Excel文件
	 * @return
	 * @throws Exception
	 */
	public void buildCheckPendingVehicle(List<CheckPendingVehiclePO> personList) throws IOException{
		int i = 0;
		for (CheckPendingVehiclePO p : personList) {
			if(p != null){
//				if (p.getFullName() != null || p.getContractorName() != null || p.getCompanyCode() != null || p.getVehicleType() != null || p.getEngineNo() != null || p.getPlateColor() != null || p.getUseCharacter() != null|| p.getPlateNo() != null){
					p.setSerialId(i+1);
					i++;
//				}
			}
		}
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("data00", personList);
		dataMap.put("curDate", DateTimeUtil.getCurrDate("yyyy-MM-dd HH:mm"));
		//先生成Excel表
		XSSFWorkbook workbook = new XSSFWorkbook();
		try {
			//模板默认地址为"/WEB-INF/xls/",因此需要加模块路径
			HSExcel2 hsExcel2= new HSExcel2();
			hsExcel2.setTemplateName("xls/checkpendingvehicle");
			hsExcel2.buildExcelDocument(dataMap, workbook);

		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			try {
				workbook.close();
				workbook = null;
			} catch (IOException e) {}
		}
		copyFile("../temp/CheckPendingVehicle.xlsx", "../temp/待审批核对车辆信息"+DateTimeUtil.getCurrDate("yyyyMMddHH")+".xlsx");
	}

	/**
	 * 生成待审核照片到employeeface目录下
	 * @param oldPath  String oldPath = "../filestore"
	 * @param newPath  String newPath = "../temp/employeeface"
	 * @param personList
	 * @throws IOException
	 */
	public void buildCheckPendingPhoto(String oldPath,String newPath,List<CheckPendingPersonPO> personList) throws IOException{
		String oldImgPath = oldPath;
		String newImgPath = newPath;
		for (CheckPendingPersonPO p : personList) {
			if (p != null) {
				if (p.getDynamicFace() != null) {
					oldImgPath = oldPath + p.getDynamicFace();
					newImgPath = newPath + "/" + p.getPapersNumber() + p.getPicPath().substring(p.getPicPath().lastIndexOf("."));
					copyFile(oldImgPath,newImgPath);
				}
			}
		}
	}

	/**
	 * 取得待审核人员数据
	 * @param	params		条件参数
	 * @return
	 * @throws Exception
	 */
	public List<CheckPendingPersonPO> getCheckPendingPerson(Map<String, Object> params) {
		return (List<CheckPendingPersonPO>) sql.query("person.getCheckPendingPerson", params);
	}

	/**
	 * 取得待审核车辆数据
	 * @param	params		条件参数
	 * @return
	 * @throws Exception
	 */
	public List<CheckPendingVehiclePO> getCheckPendingVehicle(Map<String, Object> params) {
		return (List<CheckPendingVehiclePO>) sql.query("vehicle.getCheckPendingVehicle", params);
	}

	/**
	 * 压缩文件
	 * @param srcFile
	 * @param outputStream
	 * @throws RuntimeException
	 */
	public void zipFiles(List<File> srcFile, OutputStream outputStream) throws RuntimeException{
		ZipOutputStream zipOutputStream = null;
		try {
			zipOutputStream = new ZipOutputStream(outputStream);
			for (File srcfile:srcFile) {
				if (srcfile.isFile()){
					byte[] bytes = new byte[1024];
					zipOutputStream.putNextEntry(new ZipEntry(srcfile.getName()));
					int len;
					FileInputStream fileInputStream = new FileInputStream(srcfile);
					while ((len = fileInputStream.read(bytes)) != -1){
						zipOutputStream.write(bytes, 0,len);
					}
					zipOutputStream.closeEntry();
					fileInputStream.close();
				}else if (srcfile.isDirectory()){
					//传入文件为文件夹时，调用文件夹压缩方法
					zipDir(srcfile,zipOutputStream,srcfile.getName());
					zipOutputStream.closeEntry();
				}
			}
			zipOutputStream.closeEntry();
			zipOutputStream.close();
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	/**
	 * 文件夹压缩
	 * @param srcFile
	 * @param zipOutputStream
	 * @param name
	 * @throws Exception
	 */
	public void zipDir(File srcFile,ZipOutputStream zipOutputStream,String name) throws Exception{
		byte[] bytes = new byte[1024];
		if (srcFile.isFile()){
			zipOutputStream.putNextEntry(new ZipEntry(name));
			int len;
			FileInputStream fileInputStream = new FileInputStream(srcFile);
			while ((len = fileInputStream.read(bytes)) != -1){
				zipOutputStream.write(bytes,0,len);
			}
			zipOutputStream.closeEntry();
			fileInputStream.close();
		}else {
			File[] files = srcFile.listFiles();
			if (files == null || files.length == 0){
				zipOutputStream.putNextEntry(new ZipEntry(name + "/"));
				zipOutputStream.closeEntry();
			}else{
				for (File file:files) {
					zipDir(file,zipOutputStream,name+"/"+ file.getName());
				}
			}
		}
	}

	/**
	 *复制文件
	 * @param oldPath  String oldPath = "../filestore";
	 * @param newPath  String newPath = "../temp/employeeface";
	 * @throws IOException
	 */
	public void copyFile(String oldPath,String newPath) throws IOException {

		File oldFile = new File(oldPath);
		File newFile = new File(newPath);
		if (oldFile.isDirectory()) {
			File[] files = oldFile.listFiles();
			for (File f:files) {
				InputStream inputStream = new FileInputStream(f);
				FileOutputStream fileOutputStream = new FileOutputStream(new File(newPath));
				byte[] bytes = new byte[1024];
				int len;
				while ((len = inputStream.read(bytes)) != -1) {
					fileOutputStream.write(bytes, 0, len);
				}
				inputStream.close();
				fileOutputStream.close();
			}
		}else {
			InputStream inputStream = new FileInputStream(oldFile);
			FileOutputStream fileOutputStream = new FileOutputStream(new File(newPath));
			byte[] bytes = new byte[1024];
			int len;
			while ((len = inputStream.read(bytes)) != -1) {
				fileOutputStream.write(bytes, 0, len);
			}
			inputStream.close();
			fileOutputStream.close();
		}
	}

	/**
	 * 清空文件
	 * @param path
	 */
	public void delFile(String path){
		File file = new File(path);
		if (!file.isDirectory()){
			file.delete();
		}else if(file.isDirectory()) {
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				File f = new File(file.getPath() + "/" + files[i].getName());
				if (f.isFile()) {
					f.delete();
				} else if (f.isDirectory())
				{
					delFile(file.getPath() + "/" + files[i].getName());
					String fPath = f.getPath();
					if (fPath != path){
						f.delete();
					}
				}
			}
		}
	}

	/**
	 * 删除过期文件
	 * @param before
	 * @param after
	 * @param path
	 */
	public void delExpiredFile(int before,int after,String path){ //before 从当前日期往前推的天数 //after 以往前推的日期为起点，删除after天数文件 path 清楚当前目录下过期文件
		File file = new File(path);
		Date date = new Date();
		Date beforeDate = DateTimeUtil.calendarAdd(date,5,-before);
		String[] dateString = new String[after];

		for (int i = 0; i < after; i++) {
			dateString[i] = DateTimeUtil.dateToString(DateTimeUtil.calendarAdd(beforeDate,5,i),"yyyyMMdd");
			if (file.isDirectory()){
				File[] files = file.listFiles();
				for (File f:files) {
					if (f.getName().indexOf(dateString[i]) != -1){
						f.delete();
					}
				}
			}else {
				if (file.getName().indexOf(dateString[i]) != -1){
					file.delete();
				}
			}
		}
	}
}

